#!/usr/bin/env python3
"""
快速API测试脚本
简单测试主要API接口是否可用
"""

import requests
import time
import json

def test_api_quick():
    """快速测试主要API接口"""
    base_url = "http://localhost:8000"
    admin_token = "admin_secret_token_2024"
    
    print("🧪 快速API接口测试")
    print("="*50)
    print("⚠️  请确保服务器已启动: python backend/main.py")
    print()
    
    # 测试接口列表
    tests = [
        # 基础接口
        ("GET", "/health", None, None, "健康检查"),
        ("GET", "/", None, None, "根路径"),
        
        # 学生端API
        ("GET", "/api/questions", None, None, "获取题目列表"),
        ("GET", "/api/scores/1", None, None, "获取班级成绩"),
        ("GET", "/api/class-analysis/1", None, None, "班级分析"),
        
        # 新增的学生API
        ("GET", "/api/student-records?class_id=1", None, None, "学生记录查询"),
        
        # 教师端API
        ("GET", "/api/teacher/dashboard?class_id=1", None, None, "教师数据看板"),
        
        # 管理员API
        ("GET", "/admin/questions", {"Authorization": f"Bearer {admin_token}"}, None, "获取所有题目"),
        ("GET", "/admin/question-banks", {"Authorization": f"Bearer {admin_token}"}, None, "获取所有题库"),
        ("GET", "/admin/question-banks/active", {"Authorization": f"Bearer {admin_token}"}, None, "获取激活题库"),
    ]
    
    results = []
    
    for method, path, headers, data, description in tests:
        url = f"{base_url}{path}"
        
        try:
            if method == "GET":
                response = requests.get(url, headers=headers, timeout=5)
            elif method == "POST":
                response = requests.post(url, headers=headers, json=data, timeout=5)
            else:
                continue
            
            success = response.status_code in [200, 201]
            status_icon = "✅" if success else "❌"
            
            print(f"{status_icon} {description} ({response.status_code})")
            
            if success and response.content:
                try:
                    data = response.json()
                    if isinstance(data, list):
                        print(f"   返回: 列表，{len(data)} 项")
                    elif isinstance(data, dict):
                        if 'status' in data:
                            print(f"   状态: {data.get('status')}")
                        else:
                            print(f"   返回: 对象，{len(data)} 个字段")
                except:
                    print(f"   返回: 非JSON数据")
            
            results.append(success)
            
        except requests.exceptions.ConnectionError:
            print(f"❌ {description} - 连接失败")
            print("   请确保服务器正在运行: python backend/main.py")
            results.append(False)
        except Exception as e:
            print(f"❌ {description} - 错误: {str(e)[:50]}")
            results.append(False)
    
    # 统计结果
    total = len(results)
    passed = sum(results)
    
    print()
    print("📊 测试结果")
    print("-" * 30)
    print(f"总测试数: {total}")
    print(f"通过: {passed} ✅")
    print(f"失败: {total - passed} ❌")
    print(f"成功率: {(passed/total*100):.1f}%")
    
    if passed == total:
        print("\n🎉 所有API接口测试通过！")
        print("✅ API_README.md文档中的接口都可以正常调用")
    elif passed > total * 0.8:
        print("\n✅ 大部分API接口正常工作")
        print("⚠️  少数接口可能需要检查")
    else:
        print("\n⚠️  多个API接口无法访问")
        print("🔧 请检查服务器是否正常启动")
    
    return passed == total

def test_specific_endpoints():
    """测试特定的新增接口"""
    base_url = "http://localhost:8000"
    
    print("\n🔍 测试新增的API接口")
    print("-" * 30)
    
    # 测试健康检查
    try:
        response = requests.get(f"{base_url}/health", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print("✅ 健康检查接口正常")
            print(f"   状态: {data.get('status')}")
            print(f"   数据库: {data.get('database')}")
            print(f"   版本: {data.get('version')}")
        else:
            print(f"❌ 健康检查失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 健康检查异常: {e}")
    
    # 测试学生统计
    try:
        response = requests.get(f"{base_url}/api/student-statistics/测试学生?class_id=1", timeout=5)
        if response.status_code == 200:
            print("✅ 学生统计接口正常")
        elif response.status_code == 404:
            print("✅ 学生统计接口正常 (无数据)")
        else:
            print(f"❌ 学生统计失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 学生统计异常: {e}")
    
    # 测试数据导出
    try:
        export_data = {"class_id": 1, "format": "excel"}
        response = requests.post(f"{base_url}/api/teacher/dashboard/export", json=export_data, timeout=5)
        if response.status_code == 200:
            print("✅ 数据导出接口正常")
        else:
            print(f"❌ 数据导出失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 数据导出异常: {e}")

def main():
    print("🚀 API接口快速验证工具")
    print("="*50)
    print("本工具将快速测试API_README.md中的主要接口")
    print()
    
    # 检查服务器连接
    try:
        response = requests.get("http://localhost:8000/health", timeout=3)
        print("✅ 服务器连接正常")
    except:
        print("❌ 无法连接到服务器")
        print("请先启动服务器:")
        print("  方法1: python backend/main.py")
        print("  方法2: restart.bat")
        print()
        return
    
    # 运行快速测试
    success = test_api_quick()
    
    # 测试特定接口
    test_specific_endpoints()
    
    print("\n" + "="*50)
    if success:
        print("🎉 API接口验证完成！")
        print("✅ API_README.md文档准确，所有接口都可正常调用")
    else:
        print("⚠️  部分API接口需要检查")
        print("💡 建议运行完整测试: python comprehensive_api_test.py")
    
    print("\n📚 相关文档:")
    print("  - API_README.md - 完整API文档")
    print("  - api_validation_summary.md - 验证总结")
    print("  - comprehensive_api_test.py - 完整测试脚本")

if __name__ == "__main__":
    main()
